// Copyright (C) 2019-2020 star.engine at outlook dot com
//
// This file is part of StarEngine
//
// StarEngine is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// StarEngine is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with StarEngine.  If not, see <https://www.gnu.org/licenses/>.

#include "SDX12DescriptorArray.h"

namespace Star::Graphics::Render {

DX12DescriptorArrayBase::DX12DescriptorArrayBase(ID3D12Device* pDevice,
    uint32_t sz, D3D12_DESCRIPTOR_HEAP_TYPE type, D3D12_DESCRIPTOR_HEAP_FLAGS flags
) {
    resize(pDevice, sz, type, flags);
}

void DX12DescriptorArrayBase::resize(ID3D12Device* pDevice, uint32_t sz,
    D3D12_DESCRIPTOR_HEAP_TYPE type, D3D12_DESCRIPTOR_HEAP_FLAGS flags
) {
    if (sz == mArraySize)
        return;

    mHeap = nullptr;
    mArraySize = sz;
    D3D12_DESCRIPTOR_HEAP_DESC desc;
    ZeroMemory(&desc, sizeof(desc));
    desc.NumDescriptors = sz;
    desc.Type = type;
    desc.Flags = flags;
    V(pDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(mHeap.put())));
    mDescriptorSize = pDevice->GetDescriptorHandleIncrementSize(type);
    mCpuBase = mHeap->GetCPUDescriptorHandleForHeapStart();
    mGpuBase = mHeap->GetGPUDescriptorHandleForHeapStart();
}

void DX12DescriptorArrayBase::clear() noexcept {
    mHeap = nullptr;
    mArraySize = 0;
    mDescriptorSize = 0;
    mCpuBase = {};
    mGpuBase = {};
}

}
